package gstudio.mp3;

import gstudio.data.DataIO;
import gstudio.data.IData;
import gstudio.data.RuntimeDataManager;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;

/*
 * 先确定 satzlist,
 * 然后cutcomp找到相应的item
 */
public class Mp3CutTableComposite extends Composite {
	public static void main(String[] args) {
		Display display = new Display();
		Shell shell = new Shell(display);
		shell.setText("Text Table Editor");
		shell.setLayout(new FillLayout());
		Mp3CutTableComposite mtc = new Mp3CutTableComposite(shell, SWT.NONE);

		for (int i = 0; i < 10; i++) {
			mtc.addSatz("satz" + i);
			mtc.addSatzComp(100, 200, "input", "output");
		}
		shell.open();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		display.dispose();
	}

	private Table table;
	private int currentCutItemIndex = -1;
	private String subMp3Dir;
	private String mp3Path, textTitle, textContent;

	public Mp3CutTableComposite(Composite parent, int style) {
		super(parent, style);
		init();
	}

	public void addSatz(final String satz) {
		TableItem item = new TableItem(table, SWT.NONE);
		item.setChecked(true);
		item.setText(1, satz);
		table.update();
	}

	public void addSatzComp(int start, int end, String inputMp3Path,
			String outputMp3Path) {
		currentCutItemIndex++;
		mp3Path = inputMp3Path;
		if (subMp3Dir == null) {
			File file = new File(inputMp3Path);
			if (file.exists() && file.canRead()) {
				subMp3Dir = file.getName();
				subMp3Dir = subMp3Dir.replaceAll(".mp3", "");
				DataIO.getInstance().createMp3SubDir(subMp3Dir);
				subMp3Dir = DataIO.getInstance().getMp3Dir() + "/" + subMp3Dir;
			}
		}
		TableItem item = null;
		if (currentCutItemIndex < table.getItemCount()) {
			item = table.getItem(currentCutItemIndex);
		}

		if (item == null) {
			item = new TableItem(table, SWT.NONE);
			item.setChecked(true);
		}
		Mp3CutWithSpinnerComposite cutWithSpinner = new Mp3CutWithSpinnerComposite(
				table, SWT.NONE);
		cutWithSpinner.setInput(start, end, inputMp3Path, outputMp3Path);
		{
			TableEditor editor = new TableEditor(table);
			editor.setEditor(cutWithSpinner, item, 0);
			editor.grabHorizontal = true;
			editor.minimumHeight = cutWithSpinner.getSize().y;
			editor.minimumWidth = cutWithSpinner.getSize().x;
		}

		item.setText(0, outputMp3Path);
		table.redraw();
	}

	private void init() {
		this.setLayout(new FillLayout());

		table = new Table(this, SWT.SINGLE | SWT.FULL_SELECTION
				| SWT.HIDE_SELECTION | SWT.CHECK);
		table.addListener(SWT.Resize, new Listener() {

			@Override
			public void handleEvent(Event arg0) {
				TableColumn tc0 = table.getColumn(0);
				TableColumn tc1 = table.getColumn(1);

				tc1.setWidth(table.getSize().x - tc0.getWidth());

			}
		});

		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		{
			TableColumn tc = new TableColumn(table, SWT.NONE);
			tc.setText("mp3");
			tc.setWidth(400);

		}

		{
			TableColumn tc = new TableColumn(table, SWT.NONE);
			tc.setText("satz");
			tc.setWidth(500);
		}

		table.addListener(SWT.MouseDoubleClick, new Listener() {

			@Override
			public void handleEvent(Event arg0) {

				final Text text = new Text(table, SWT.NONE);
				TableItem[] its = table.getSelection();
				if (its == null || its.length < 1)
					return;

				final TableItem item = its[0];

				text.setText(item.getText(1));

				TableEditor editor = new TableEditor(table);
				editor.setEditor(text, item, 1);
				editor.grabHorizontal = true;
				editor.minimumHeight = text.getSize().y;
				editor.minimumWidth = text.getSize().x;

				text.addListener(SWT.FocusOut, new Listener() {
					public void handleEvent(Event arg0) {
						item.setText(1, text.getText());
						text.dispose();

					}
				});
				table.update();
			}
		});

		table.addListener(SWT.MouseUp, new Listener() {

			@Override
			public void handleEvent(Event arg0) {
				if (arg0.button != 3)
					return;
				TableItem[] its = table.getSelection();
				if (its == null || its.length < 1)
					return;

				final TableItem item = its[0];

				Menu menu = new Menu(table.getShell(), SWT.POP_UP);
				{
					MenuItem mi = new MenuItem(menu, SWT.NONE);
					mi.setText("Add");
					mi.addListener(SWT.Selection, new Listener() {
						public void handleEvent(Event arg0) {
							addSatz("");
							moveItemDown(item);
						}
					});
				}

				{
					MenuItem mi = new MenuItem(menu, SWT.NONE);
					mi.setText("Del");
					mi.addListener(SWT.Selection, new Listener() {
						public void handleEvent(Event arg0) {
							moveItemUp(item);
						}
					});
				}
				{

					new MenuItem(menu, SWT.SEPARATOR);
				}
				{

					MenuItem mi = new MenuItem(menu, SWT.NONE);
					mi.setText("Go");
					mi.addListener(SWT.Selection, new Listener() {
						public void handleEvent(Event arg0) {
							RuntimeDataManager rdm = RuntimeDataManager
									.getInstance();

							IData artikel = rdm.getCurrentData();
							if (artikel != null) {
								String ids = "";
								rdm.removeSatzOfArtikel(artikel);
								for (TableItem ti : table.getItems()) {
									String tiText = ti.getText();
									if (ti.getChecked() && tiText != null
											&& tiText.length() > 0) {
										IData satz = new IData();
										satz.setValueOf("title", ti.getText(1));
										satz.setValueOf("pids",
												artikel.getValueOf("id"));
										String fileToCopy = ti.getText(0);
										File file = new File(fileToCopy);
										String newFileName = subMp3Dir + "/"
												+ file.getName();
										File newFile = new File(newFileName);
										DataIO.getInstance().copyFile(file,
												newFile);
										satz.setValueOf("mp3", newFileName);
										RuntimeDataManager.getInstance()
												.addSatz(satz);
										ids += " " + satz.getValueOf("id");
									}
								}
								artikel.setValueOf("cids", ids);
							}
							DataIO.getInstance().saveXML();
						}
					});

					MenuItem toSatz = new MenuItem(menu, SWT.NONE);
					toSatz.setText("输出句子和mp3位置");
					toSatz.addListener(SWT.Selection, new Listener() {
						public void handleEvent(Event arg0) {
							Control[] cls = table.getTabList();
							TableItem ti;
							Control c;
							Document doc = DocumentHelper.createDocument();
							doc.setXMLEncoding("utf-8");

							Element root = doc.addElement("root");
							Element texts = root.addElement("texts");
							Element text = texts.addElement("text");
							text.addElement("title").setText(textTitle);
							text.addElement("de").setText(textContent);

							Element satzs = root.addElement("satzs");
							String media = mp3Path;
							int j = media.lastIndexOf("\\");
							if (j > 0) {
								media = media.substring(j+1);
							}
							j = media.lastIndexOf("/");
							if (j > 0) {
								media = media.substring(j+1);
							}

							for (int i = 0; i < table.getItemCount(); i++) {
								ti = table.getItem(i);
								String tiText = ti.getText();
								if (ti.getChecked() && tiText != null
										&& tiText.length() > 0) {
									c = cls[i];
									if (c instanceof Mp3CutWithSpinnerComposite) {
										int[] xy = ((Mp3CutWithSpinnerComposite) c)
												.getStartEnd();
										Element satz = satzs.addElement("satz");
										satz.addElement("media_s").setText(
												xy[0] + "");
										satz.addElement("media_e").setText(
												xy[1] + "");
										satz.addElement("de").setText(
												ti.getText(1).trim());
										satz.addElement("media").setText(media);
									}

								}
							}

							DataIO.getInstance().writeDoc(doc, DataIO.getInstance().getGsRootPath()+"/alles.xml");
						}
					});

				}
				menu.setVisible(true);

			}
		});

	}

	private void moveItemDown(TableItem item) {

		for (int i = table.getItemCount() - 1; i > -1; i--) {
			TableItem ti = table.getItem(i);
			if (i > 0) {
				TableItem pre = table.getItem(i - 1);
				ti.setText(1, pre.getText(1));
			}
			if (ti.equals(item)) {
				item.setText(1, "");
				break;
			}
		}

	}

	private void moveItemUp(TableItem item) {
		int len = table.getItemCount();
		boolean start = false;

		for (int i = 0; i < len; i++) {
			TableItem ti = table.getItem(i);
			if (ti.equals(item)) {
				start = true;
			}

			if (start) {
				if (i < len - 1) {
					TableItem next = table.getItem(i + 1);
					ti.setText(1, next.getText(1));
				} else {
					ti.setText(1, "");
				}
			}
		}
		table.update();

	}

	public void setSatzInput(List<String> list) {
		for (String s : list) {
			addSatz(s);
		}
	}

	public void setText(String text, String text2) {
		textTitle = text;
		textContent = text2;

	}

}